package com.frog.service.friend.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class FriendRelationshipUtil {

    private static final int OFFSET = 1 << 5; // 32 int长度


    /**
     * 通过关系id获取到两个用户的userId
     * 可能存在用户id为0的情况
     * 返回结果用户id大的在前
     *
     * @param relationId 关系id
     * @return Integer[]  {u1,u2}
     */
    public static Integer[] getUsersByRelationId(long relationId) {
        return new Integer[]{(int) relationId, (int) (relationId >> OFFSET)};
    }


    /**
     * 判断关系id是否包含此用户
     *
     * @param relationId 关系id
     * @param userId     用户id
     * @return true 包含 false不包含
     */
    public static boolean isUserRelation(long relationId, Integer userId) {
        if (userId == null) {
            return false;
        }
        Integer[] relation = getUsersByRelationId(relationId);
        return userId.equals(relation[0]) || userId.equals(relation[1]);

    }

    /**
     * 获取两个用户生成的关系id
     * <p>
     * 传入两个用户的id加工为好友关系的id,数据库主键
     * 两个用户不存在先后顺序,先后结果都一样
     *
     * @param userId       用户id
     * @param friendUserId 用户id
     * @return java.lang.Long 用户id异常或两个用户id相同返回null
     */
    public static Long processRelationId(Integer userId, Integer friendUserId) {
        if (userId == null || friendUserId == null || userId.equals(friendUserId)) {
            return null;
        }
        long id = 0L;
        if (userId < friendUserId) {
            userId = userId ^ friendUserId;
            friendUserId = userId ^ friendUserId;
            userId = userId ^ friendUserId;
        }
        id = id | userId;
        id = id | ((long) friendUserId << OFFSET);
        return id;
    }


    public static List<String> processRelationId(String userId, String... friendUserId) {
        List<String> ids = new ArrayList<>();
        if (StringUtils.isBlank(userId) || friendUserId == null) return ids;
        for (String fid : friendUserId) {
            try {
                Long id = processRelationId(Integer.parseInt(userId), Integer.parseInt(fid));
                if (id == null) continue;
                ids.add(String.valueOf(id));
            } catch (Exception e) {
                log.info("processRelationId userId=={}, fid=={}", userId, fid, e);
            }

        }
        return ids;
    }

}
